package com.pfzy.lib.net.exception;

import android.app.Application;
import android.os.AsyncTask;

import com.pfzy.lib.net.BaseEntity;
import com.pfzy.lib.net.utils.NetUtil;
import com.pfzy.lib.sdk.log.UXLog;

import java.util.HashMap;

import javax.net.ssl.SSLHandshakeException;

/**
 * 异常拦截器
 */
public class ExceptionInterceptor implements IExceptionInterceptor {
    private Application mApplication;
    private volatile boolean mIsSendErrorData;

    public ExceptionInterceptor(Application application) {
        this.mApplication = application;
    }

    @Override
    public CCHttpException onBizException(BaseEntity baseEntity) {
        return null;
    }

    @Override
    public CCHttpException onHttpException(Throwable e) {
        try {
            UXLog.e("http_error", e + ":::" + e.getMessage());
        } catch (Throwable error) {
            error.printStackTrace();
        }
        if (e instanceof SSLHandshakeException) {
            sendErrorData(e.getMessage());
            return new CCHttpException(ExceptionHandler.ERROR.SSL_ERROR, "网络繁忙");
        }
        return null;
    }

    private void sendErrorData(final String errorMsg) {
        if (!this.mIsSendErrorData) {
            this.mIsSendErrorData = true;
            AsyncTask.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        HashMap<String, String> customMap = new HashMap<>();
                        customMap.put("error_message", errorMsg);
                        customMap.put("network_type", NetUtil.getNetworkType(ExceptionInterceptor.this.mApplication).name());
                        customMap.put("net_available", "" + NetUtil.isAvailableByPing());
                        customMap.put("current_date", "" + System.currentTimeMillis());
                        UXLog.e("http_error", customMap.toString());
                    } catch (Throwable exception) {
                        exception.printStackTrace();
                    }
                    ExceptionInterceptor.this.mIsSendErrorData = false;
                }
            });
        }
    }
}
